/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package procesos;

import controladores.ResultTestJpaController;
import controladores.ResultadoJpaController;
import entidades.RespAlternativas;
import entidades.ResultTest;
import entidades.Resultado;
import entidades.Test;
import java.awt.Color;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JRadioButton;

/**
 *
 * @author Oswl_C
 */
public class RealizarTest extends javax.swing.JInternalFrame {

    private Test test;
    JLabel[] label = new JLabel[100];
    JLabel[][] lblResp = new JLabel[100][3];
    JRadioButton[][] jrb = new JRadioButton[100][3];
    ButtonGroup[] grupo = new ButtonGroup[100];
    RespAlternativas[][] resp = new RespAlternativas[100][3];
    private Integer velocidad;

    /**
     * Creates new form RealizarTest
     */
    public RealizarTest() {
        initComponents();
    }

    public RealizarTest(Test test, Integer velocidad) {
        initComponents();
        this.test = test;
        this.velocidad = velocidad;
        ejecutarTest();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("lecturadb?zeroDateTimeBehavior=convertToNullPU").createEntityManager();
        itemTestQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT i FROM ItemTest i");
        itemTestList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : itemTestQuery.getResultList();
        respAlternativasQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT r FROM RespAlternativas r");
        respAlternativasList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : respAlternativasQuery.getResultList();
        jLTituloTest = new javax.swing.JLabel();
        jLDescri = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        lblNota = new javax.swing.JLabel();
        lblPorc = new javax.swing.JLabel();
        lblVel = new javax.swing.JLabel();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setAutoscrolls(true);

        jLTituloTest.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        jLDescri.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        jButton1.setText("Finalizar y Guardar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        lblNota.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        lblNota.setForeground(new java.awt.Color(0, 51, 204));
        lblNota.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        lblPorc.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        lblPorc.setForeground(new java.awt.Color(0, 51, 204));
        lblPorc.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        lblVel.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        lblVel.setForeground(new java.awt.Color(0, 51, 204));
        lblVel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLTituloTest, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLDescri, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 382, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(lblVel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblPorc, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(lblNota, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLTituloTest, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLDescri, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblNota, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblVel, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblPorc, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(119, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        guardar();
    }//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.persistence.EntityManager entityManager;
    private java.util.List<entidades.ItemTest> itemTestList;
    private javax.persistence.Query itemTestQuery;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLDescri;
    private javax.swing.JLabel jLTituloTest;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lblNota;
    private javax.swing.JLabel lblPorc;
    private javax.swing.JLabel lblVel;
    private java.util.List<entidades.RespAlternativas> respAlternativasList;
    private javax.persistence.Query respAlternativasQuery;
    // End of variables declaration//GEN-END:variables

    private void ejecutarTest() {
        itemTestList = entityManager.createQuery("SELECT i FROM ItemTest i WHERE i.tesCodigo.tesCodigo = :testCod").setParameter("testCod", test.getTesCodigo()).getResultList();
        this.jLTituloTest.setText(test.getTesTitulo());
        this.jLDescri.setText(test.getTesDescri());

        for (int i = 0; i < 5; i++) {
            label[i] = new JLabel(itemTestList.get(i).getItePregunta());
            label[i].setBounds(10, 100 * i + 100, 1000, 30);
            grupo[i] = new ButtonGroup();
            add(label[i]);
            int posBot = 0;
            respAlternativasList = entityManager.createQuery("SELECT r FROM RespAlternativas r WHERE r.iteCodigo = :pregCod").setParameter("pregCod", itemTestList.get(i)).getResultList();
            for (int j = 0; j < 3; j++) {
                jrb[i][j] = new JRadioButton(respAlternativasList.get(j).getRalRespAlt());
                resp[i][j] = respAlternativasList.get(j);
                grupo[i].add(jrb[i][j]);
                posBot = posBot + 20;
                jrb[i][j].setBounds(20, 100 * i + posBot + 100, 1000, 30);
                add(jrb[i][j]);
            }

        }
    }

    private void guardar() {
        ResultTest rt = new ResultTest();
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 3; j++) {
                if (jrb[i][j].isSelected()) {
                    rt.setAluCedula(LecturaMDI.cedula);
                    rt.setIteCodigo(itemTestList.get(i).getIteCodigo());
                    rt.setRalCodigo(resp[i][j].getRalCodigo());
                    rt.setRteCodigo(0);
                    ResultTestJpaController rtc = new ResultTestJpaController(entityManager.getEntityManagerFactory());
                    rtc.create(rt);
                }
            }
        }

        Integer nota = 0;
        for (int i = 0; i < 5; i++) {
            int posBot = 0;
            respAlternativasList = entityManager.createQuery("SELECT r FROM RespAlternativas r WHERE r.iteCodigo = :pregCod").setParameter("pregCod", itemTestList.get(i)).getResultList();
            for (int j = 0; j < 3; j++) {
                resp[i][j] = respAlternativasList.get(j);
                lblResp[i][j] = new JLabel(respAlternativasList.get(j).getRalRespAlt());
                posBot = posBot + 20;
                lblResp[i][j].setBounds(20, 100 * i + posBot + 100, 1000, 30);
                if (jrb[i][j].isSelected()) {
                    if (resp[i][j].getRalTipo() == 'C') {
                        lblResp[i][j].setForeground(Color.green);
                        nota++;
                    } else {
                        lblResp[i][j].setForeground(Color.red);
                    }
                }
                jrb[i][j].setVisible(isIcon);
                add(lblResp[i][j]);
            }

        }
        
        Double porcentaje = nota.doubleValue()/5*100;
        lblNota.setText("Nota: " + nota.toString() + "/5");
        lblVel.setText("Velocidad: " + velocidad.toString() + "ppm");
        lblPorc.setText("Comprensión: " + porcentaje.toString() + "%");
        
        
        Resultado resultado = new Resultado(0);
        resultado.setCedula(LecturaMDI.cedula);
        Integer dia = (Integer) entityManager.createQuery("SELECT max(r.dia) FROM Resultado r WHERE r.cedula = :cedula").setParameter("cedula", LecturaMDI.cedula).getSingleResult();
        if(dia==null) dia =0;
        resultado.setDia(dia + 1);        
        resultado.setPorcentaje(porcentaje);
        resultado.setVelocidad(velocidad);
        ResultadoJpaController restCont = new ResultadoJpaController(entityManager.getEntityManagerFactory());
        restCont.create(resultado);
    }   

}
